<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="电梯名称" prop="elevatorName">
            <el-input v-model="queryParams.elevatorName" placeholder="请输入电梯名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['iot:annualInspection:add']" icon="Plus" plain type="primary" @click="handleAdd"> 手动分配 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['iot:annualInspection:remove']" :disabled="multiple" icon="Delete" plain type="danger" @click="handleDelete()"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['iot:annualInspection:export']" icon="Download" plain type="warning" @click="handleExport">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="annualInspectionList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="电梯名称" align="center" prop="elevatorName" />
        <el-table-column label="年检日期" align="center" prop="annualDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.annualDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否检查限速器" prop="checkSpeedLimiter">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.checkSpeedLimiter" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否年检通过" prop="checkThrough">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.checkThrough" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="年检状态" prop="inspectionStatus">
          <template #default="scope">
            <dict-tag :options="iot_annual_type" :value="scope.row.inspectionStatus" />
          </template>
        </el-table-column>
        <el-table-column label="年检负责人" align="center" prop="headMan" />
        <el-table-column label="年检启动日期" align="center" prop="startTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="年检完成时间" align="center" prop="completionTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.completionTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="年检描述" align="center" prop="inspectionContext" />
        <el-table-column label="年检图片" align="center" prop="inspectionImg" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['iot:annualInspection:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改电梯年检管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="annualInspectionFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择年检计划:" label-width="120px" prop="planId">
          <el-select v-model="form.planId" filterable placeholder="请选择年检计划" style="width: 240px">
            <el-option v-for="item in annualPlanList" :key="item.planId" :label="item.elevatorName" :value="item.planId" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AnnualInspection" lang="ts">
import {
  addAnnualInspection,
  delAnnualInspection,
  listAnnualInspection,
  updateAnnualInspection
} from "@/api/iot/annualInspection";
import { AnnualInspectionForm, AnnualInspectionQuery, AnnualInspectionVO } from "@/api/iot/annualInspection/types";
import { listAnnualPlan } from "@/api/iot/annualPlan";
import { parseTime } from "@/utils/ruoyi";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { iot_annual_type, sys_yes_no } = toRefs<any>(proxy?.useDict("iot_annual_type", "sys_yes_no"));
const annualInspectionList = ref<AnnualInspectionVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const annualPlanList = ref<Array<any>>([]);

const queryFormRef = ref<ElFormInstance>();
const annualInspectionFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ""
});

const initFormData: AnnualInspectionForm = {
  inspectionId: undefined,
  planId: undefined,
  elevatorName: undefined,
  annualDate: undefined,
  checkSpeedLimiter: undefined,
  checkThrough: undefined,
  inspectionStatus: undefined,
  headMan: undefined,
  headUserId: undefined,
  startTime: undefined,
  completionTime: undefined,
  inspectionContext: undefined,
  inspectionImg: undefined,
  remark: undefined
};
const data = reactive<PageData<AnnualInspectionForm, AnnualInspectionQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planId: undefined,
    elevatorName: undefined,
    annualDate: undefined,
    checkSpeedLimiter: undefined,
    checkThrough: undefined,
    inspectionStatus: undefined,
    headMan: undefined,
    headUserId: undefined,
    startTime: undefined,
    completionTime: undefined,
    inspectionContext: undefined,
    inspectionImg: undefined,
    params: {}
  },
  rules: {
    inspectionId: [
      { required: true, message: "年检ID不能为空", trigger: "blur" }
    ],
    planId: [
      { required: true, message: "关联计划ID不能为空", trigger: "blur" }
    ],
    elevatorName: [
      { required: true, message: "电梯名称不能为空", trigger: "blur" }
    ],
    annualDate: [
      { required: true, message: "年检日期不能为空", trigger: "blur" }
    ],
    checkSpeedLimiter: [
      { required: true, message: "是否检查限速器不能为空", trigger: "blur" }
    ],
    checkThrough: [
      { required: true, message: "是否年检通过不能为空", trigger: "blur" }
    ],
    inspectionStatus: [
      { required: true, message: "年检状态(0.待启动,1.执行中,2.已完成,3.已超期)不能为空", trigger: "change" }
    ],
    headMan: [
      { required: true, message: "年检负责人不能为空", trigger: "blur" }
    ],
    headUserId: [
      { required: true, message: "负责人ID不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "年检启动日期不能为空", trigger: "blur" }
    ],
    completionTime: [
      { required: true, message: "年检完成时间不能为空", trigger: "blur" }
    ],
    inspectionContext: [
      { required: true, message: "年检描述不能为空", trigger: "blur" }
    ],
    inspectionImg: [
      { required: true, message: "年检图片不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询电梯年检管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAnnualInspection(queryParams.value);
  annualInspectionList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  annualInspectionFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: AnnualInspectionVO[]) => {
  ids.value = selection.map(item => item.inspectionId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加电梯年检管理";
  let res = await listAnnualPlan();
  annualPlanList.value = res.rows;
};

/** 提交按钮 */
const submitForm = () => {
  annualInspectionFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.inspectionId) {
        await updateAnnualInspection(form.value).finally(() => buttonLoading.value = false);
      } else {
        form.value.elevatorName = annualPlanList.value.find(item => item.planId === form.value.planId)?.elevatorName;
        await addAnnualInspection(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: AnnualInspectionVO) => {
  const _inspectionIds = row?.inspectionId || ids.value;
  await proxy?.$modal.confirm("是否确认删除电梯年检管理编号为\"" + _inspectionIds + "\"的数据项？").finally(() => loading.value = false);
  await delAnnualInspection(_inspectionIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download("iot/annualInspection/export", {
    ...queryParams.value
  }, `annualInspection_${new Date().getTime()}.xlsx`);
};

onMounted(() => {
  getList();
});
</script>
